// dao/MovieDAO.java
package main.java.com.cinema.dao;

import main.java.com.cinema.model.Movie;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

public class MovieDAO {
    private static final String MOVIE_FILE = "movies.txt";

    public List<Movie> findAll() {
        List<Movie> movies = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(MOVIE_FILE))) {
            String line;
            while ((line = reader.readLine()) != null) {
                Movie movie = parseMovieFromLine(line);
                if (movie != null) {
                    movies.add(movie);
                }
            }
        } catch (FileNotFoundException e) {
            // 文件不存在，返回空列表
        } catch (IOException e) {
            e.printStackTrace();
        }
        return movies;
    }

    public Movie findById(String movieId) {
        List<Movie> movies = findAll();
        for (Movie movie : movies) {
            if (movie.getId().equals(movieId)) {
                return movie;
            }
        }
        return null;
    }

    public List<Movie> searchMovies(String title, String director, String actor) {
        List<Movie> movies = findAll();
        List<Movie> result = new ArrayList<>();

        for (Movie movie : movies) {
            boolean match = false;

            // 按片名搜索
            if (title != null && !title.isEmpty() &&
                    movie.getTitle().toLowerCase().contains(title.toLowerCase())) {
                match = true;
            }

            // 按导演搜索
            if (director != null && !director.isEmpty() &&
                    movie.getDirector().toLowerCase().contains(director.toLowerCase())) {
                match = true;
            }

            // 按主演搜索
            if (actor != null && !actor.isEmpty() && movie.getActors() != null) {
                for (String a : movie.getActors()) {
                    if (a.toLowerCase().contains(actor.toLowerCase())) {
                        match = true;
                        break;
                    }
                }
            }

            // 如果没有指定搜索条件，则包含所有电影
            if ((title == null || title.isEmpty()) &&
                    (director == null || director.isEmpty()) &&
                    (actor == null || actor.isEmpty())) {
                match = true;
            }

            if (match) {
                result.add(movie);
            }
        }

        return result;
    }

    public boolean save(Movie movie) {
        List<Movie> movies = findAll();
        movies.add(movie);
        return saveAll(movies);
    }

    public boolean update(Movie movie) {
        List<Movie> movies = findAll();
        for (int i = 0; i < movies.size(); i++) {
            if (movies.get(i).getId().equals(movie.getId())) {
                movies.set(i, movie);
                return saveAll(movies);
            }
        }
        return false;
    }

    public boolean delete(String movieId) {
        List<Movie> movies = findAll();
        movies.removeIf(movie -> movie.getId().equals(movieId));
        return saveAll(movies);
    }

    private boolean saveAll(List<Movie> movies) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(MOVIE_FILE))) {
            for (Movie movie : movies) {
                writer.write(movieToLine(movie));
                writer.newLine();
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    private String movieToLine(Movie movie) {
        StringBuilder sb = new StringBuilder();
        sb.append(movie.getId()).append("|");
        sb.append(movie.getTitle()).append("|");
        sb.append(movie.getDirector()).append("|");
        sb.append(movie.getSynopsis()).append("|");
        sb.append(movie.getDuration()).append("|");
        sb.append(movie.getRating()).append("|");

        // 处理演员数组
        if (movie.getActors() != null && movie.getActors().length > 0) {
            sb.append(String.join(",", movie.getActors()));
        }

        return sb.toString();
    }

    private Movie parseMovieFromLine(String line) {
        try {
            String[] parts = line.split("\\|");
            if (parts.length >= 6) {
                Movie movie = new Movie();
                movie.setId(parts[0]);
                movie.setTitle(parts[1]);
                movie.setDirector(parts[2]);
                movie.setSynopsis(parts[3]);
                movie.setDuration(Integer.parseInt(parts[4]));
                movie.setRating(Double.parseDouble(parts[5]));

                // 处理演员数组
                if (parts.length >= 7 && !parts[6].isEmpty()) {
                    movie.setActors(parts[6].split(","));
                } else {
                    movie.setActors(new String[0]);
                }

                return movie;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
